import React, { useState, useEffect } from 'react';
import {
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Button,
  Typography,
  Popconfirm,
  Tooltip,
  Tree,
  Descriptions,
  Row,
  Col,
  Divider,
  Card,
  Table,
  Drawer,
  Tabs,
  Spin,
} from 'antd';
import type { DataNode } from 'antd/es/tree';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  CrownOutlined,
  SafetyCertificateOutlined,
  EyeOutlined,
  ReloadOutlined,
  UserOutlined,
  MenuOutlined,
  KeyOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { Role } from '@/types/rbac';
import {
  useRoles
} from '@/hooks/business';
import { useMenus } from '@/hooks/business/useMenus';

const { Text, Title } = Typography;
const { Option } = Select;
const { Search } = Input;

const Roles: React.FC = () => {
  // 使用统一的角色管理hooks
  const {
    // 基础数据
    filteredRoles,
    loading,
    refresh,
    searchText,
    setSearchText,
    
    // 权限树数据
    permissionTree,
    permissionTreeLoading,
    
    // 工具方法
    buildPermissionTree,
    buildMenuTree,
    getMenuName,
    getPermissionNameByCode,
    getToggleStatus,
    getIsRoleActive,
    toggleStatus,
    deleteRole,
    getStatusText,
    getStatusColor,
    formatDateTime,
    
    // 角色详情相关
    viewingRole,
    viewingRoleMenus,
    viewingRolePermissions,
    detailsVisible,
    detailsLoading,
    openRoleDetails,
    closeRoleDetails,
    
    // 表单管理相关
    modalVisible,
    editingRole,
    form,
    openAddForm,
    openEditForm,
    submitForm,
    closeForm,
    
    // 权限分配相关
    permissionEditingRole,
    permissionModalVisible,
    selectedPermissions,
    selectedMenus,
    activeTab,
    permissionLoading,
    openPermissionAssignment,
    closePermissionAssignment,
    submitPermissionAssignment,
    setSelectedPermissions,
    setSelectedMenus,
    setActiveTab,
  } = useRoles();
  
  const { menuTree, loading: menuLoading, fetchMenus } = useMenus();

  // 初始化时获取菜单数据
  useEffect(() => {
    fetchMenus();
  }, []);

  // 事件处理函数
  const handleDelete = async (roleId: string) => {
    try {
      await deleteRole(roleId);
      refresh();
    } catch (error) {
      console.error('角色删除失败:', error);
    }
  };

  const handleStatusToggle = async (role: Role) => {
    try {
      const newStatus = getToggleStatus(role.status);
      await toggleStatus(role.id, newStatus);
      refresh();
    } catch (error) {
      // 错误已在hook中处理
    }
  };



  const columns: ColumnsType<Role> = [
    {
      title: '角色信息',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 250,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#64748b' }}>
            代码: {record.roleKey}
          </div>
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
      render: (remark: string) => (
        <Text type="secondary">{remark || '暂无描述'}</Text>
      ),
    },
    {
      title: '用户数量',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 120,
      align: 'center',
      render: (userCount: number) => (
        <Tag color="blue" icon={<UserOutlined />}>
          {userCount || 0} 个用户
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status: string | number, record: Role) => {
        const isActive = getIsRoleActive(status);
        return (
          <Tag 
            color={getStatusColor(status)}
            style={{ cursor: 'pointer' }}
            onClick={() => handleStatusToggle(record)}
          >
            {getStatusText(status)}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => openRoleDetails(record)}
              style={{ color: '#1890ff' }}
            />
          </Tooltip>
          <Tooltip title="权限设置">
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
              onClick={() => openPermissionAssignment(record, permissionTree)}
              style={{ color: '#722ed1' }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => openEditForm(record)}
              style={{ color: '#52c41a' }}
            />
          </Tooltip>
          <Popconfirm
            title="删除角色"
            description="确定要删除这个角色吗？删除后该角色下的用户将失去对应权限。"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
            okType="danger"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 页面标题 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <CrownOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            角色管理
          </Title>
          <Text type="secondary">管理系统角色信息和权限分配</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索角色名称、代码或描述"
            allowClear
            style={{ width: 300 }}
            onSearch={setSearchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <Button icon={<ReloadOutlined />} onClick={refresh} loading={loading}>
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={openAddForm}>
            新增角色
          </Button>
        </Space>
      </div>

      <Card bodyStyle={{ padding: 0 }}>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '24px 24px 0 24px' }}>
          <div>
            <div>
              共 {filteredRoles.length} 个角色
              {searchText && ` (搜索结果: ${filteredRoles.length} 个)`}
            </div>
          </div>
        </div>
        
        <div style={{ padding: '0 24px 24px 24px' }}>
          <Table
            columns={columns}
            dataSource={filteredRoles}
            loading={loading}
            rowKey="id"
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
              defaultPageSize: 10,
              total: filteredRoles.length,
            }}
            scroll={{ x: 1200 }}
          />
        </div>
      </Card>

      {/* 角色编辑弹窗 */}
      <Modal
        title={
          <Space>
            {editingRole ? <EditOutlined /> : <PlusOutlined />}
            <span>{editingRole ? '编辑角色' : '新增角色'}</span>
          </Space>
        }
        open={modalVisible}
        onCancel={closeForm}
        footer={null}
        width={900}
        style={{ top: 20 }}
      >
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={(values) => submitForm(values, refresh)}
        >
          <Row gutter={24}>
            <Col xs={24} md={12}>
              <Form.Item
                label="角色名称"
                name="roleName"
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input placeholder="请输入角色名称" />
              </Form.Item>
            </Col>

            <Col xs={24} md={12}>
              <Form.Item
                label="角色代码"
                name="roleKey"
                rules={[
                  { required: true, message: '请输入角色代码' },
                  { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '角色代码只能包含字母、数字和下划线，且不能以数字开头' },
                ]}
              >
                <Input placeholder="请输入角色代码" />
              </Form.Item>
            </Col>

            <Col xs={24} md={12}>
              <Form.Item
                label="角色状态"
                name="status"
                initialValue="active"
                rules={[{ required: true, message: '请选择角色状态' }]}
              >
                <Select>
                  <Option value="1">
                    <Tag color="success">启用</Tag>
                  </Option>
                  <Option value="0">
                    <Tag color="default">禁用</Tag>
                  </Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="角色描述"
            name="remark"
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 21 }}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入角色描述"
              showCount
              maxLength={200}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 3, span: 21 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingRole ? '更新' : '创建'}
              </Button>
              <Button onClick={closeForm}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限设置弹窗 */}
      <Modal
        title={
          <Space>
            <SettingOutlined style={{ color: '#1890ff' }} />
            <span>设置角色权限 - {permissionEditingRole?.roleName}</span>
          </Space>
        }
        open={permissionModalVisible}
        onCancel={closePermissionAssignment}
        onOk={() => submitPermissionAssignment(permissionTree, refresh)}
        width={900}
        style={{ top: 20 }}
      >
        <div style={{ marginBottom: 16 }}>
          <Descriptions size="small" column={2} bordered>
            <Descriptions.Item label="角色名称">{permissionEditingRole?.roleName}</Descriptions.Item>
            <Descriptions.Item label="角色代码">{permissionEditingRole?.roleKey}</Descriptions.Item>
            <Descriptions.Item label="菜单权限数量">
              <Tag color="green">{selectedMenus.length} 个菜单</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="功能权限数量">
              <Tag color="geekblue">{selectedPermissions.length} 个权限</Tag>
            </Descriptions.Item>
          </Descriptions>
        </div>
        
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            {
              key: 'menus',
              label: (
                <Space>
                  <MenuOutlined />
                  菜单分配
                </Space>
              ),
              children: (
                <div>
                  {menuLoading || permissionLoading ? (
                    <div style={{ textAlign: 'center', padding: 40 }}>
                      <Spin size="large" />
                      <div style={{ marginTop: 12 }}>
                        <Text type="secondary">正在加载菜单数据...</Text>
                      </div>
                    </div>
                  ) : (
                    <div>
                      <div style={{ marginBottom: 16, padding: '8px 12px', backgroundColor: '#f0f0f0', borderRadius: 4 }}>
                        <Text type="secondary">已选择菜单: {selectedMenus.length} 个</Text>
                        <Button 
                          type="link" 
                          size="small" 
                          onClick={() => setSelectedMenus([])}  
                          style={{ marginLeft: 8 }}
                        >
                          清空选择
                        </Button>
                      </div>
                      <Tree
                        checkable
                        checkedKeys={selectedMenus}
                        onCheck={(checkedKeys) => {
                          console.log('菜单选择变化:', checkedKeys);
                          setSelectedMenus(checkedKeys as string[]);
                        }}
                        treeData={buildMenuTree(menuTree)}
                        height={400}
                        style={{ 
                          background: '#fafafa', 
                          padding: 12, 
                          borderRadius: 6,
                        }}
                      />
                    </div>
                  )}
                </div>
              )
            },
            {
              key: 'permissions',
              label: (
                <Space>
                  <KeyOutlined />
                  权限分配
                </Space>
              ),
              children: (
                <div>
                  {permissionLoading || permissionTreeLoading ? (
                    <div style={{ textAlign: 'center', padding: 40 }}>
                      <Spin size="large" />
                      <div style={{ marginTop: 12 }}>
                        <Text type="secondary">正在加载权限数据...</Text>
                      </div>
                    </div>
                  ) : (
                    <div>
                      <div style={{ marginBottom: 16, padding: '8px 12px', backgroundColor: '#f0f0f0', borderRadius: 4 }}>
                        <Text type="secondary">已选择权限: {selectedPermissions.length} 个</Text>
                        <Button 
                          type="link" 
                          size="small" 
                          onClick={() => setSelectedPermissions([])}
                          style={{ marginLeft: 8 }}
                        >
                          清空选择
                        </Button>
                      </div>
                      <Tree
                        checkable
                        checkedKeys={selectedPermissions}
                        onCheck={(checkedKeys) => {
                          console.log('权限选择变化:', checkedKeys);
                          setSelectedPermissions(checkedKeys as string[]);
                        }}
                        treeData={buildPermissionTree(permissionTree)}
                        height={400}
                        style={{ 
                          background: '#fafafa', 
                          padding: 12, 
                          borderRadius: 6,
                        }}
                      />
                    </div>
                  )}
                </div>
              )
            }
          ]}
        />
      </Modal>

      {/* 角色详情侧边栏 */}
      <Drawer
        title={
          <Space>
            <EyeOutlined style={{ color: '#1890ff' }} />
            <span>角色详情</span>
          </Space>
        }
        open={detailsVisible}
        onClose={closeRoleDetails}
        width={600}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => {
                closeRoleDetails();
                viewingRole && openEditForm(viewingRole);
              }}
            >
              编辑
            </Button>
            <Button 
              icon={<SettingOutlined />}
              onClick={() => {
                closeRoleDetails();
                viewingRole && openPermissionAssignment(viewingRole, permissionTree);
              }}
            >
              权限设置
            </Button>
          </Space>
        }
      >
        {viewingRole && (
          <div>
            {/* 角色头部信息 */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                backgroundColor: '#1890ff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'white',
                fontSize: '28px',
                fontWeight: 'bold',
                margin: '0 auto 16px'
              }}>
                {viewingRole.roleName.charAt(0)}
              </div>
              <div>
                <Title level={4} style={{ margin: 0, color: '#262626' }}>
                  {viewingRole.roleName}
                </Title>
                <Text type="secondary" style={{ fontSize: 14 }}>
                  代码: {viewingRole.roleKey}
                </Text>
              </div>
              <div style={{ marginTop: 12 }}>
                <Tag color={getStatusColor(viewingRole.status)}>
                  {getStatusText(viewingRole.status)}
                </Tag>
              </div>
            </div>

            <Divider />

            {/* 基本信息 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <CrownOutlined style={{ marginRight: 8 }} />
              基本信息
            </Title>
            <Descriptions bordered column={1} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="角色名称">{viewingRole.roleName}</Descriptions.Item>
              <Descriptions.Item label="角色代码">{viewingRole.roleKey}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getStatusColor(viewingRole.status)}>
                  {getStatusText(viewingRole.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="权限统计">
                <Space>
                  <Tag color="green" icon={<MenuOutlined />}>
                    菜单: {viewingRoleMenus.length}
                  </Tag>
                  <Tag color="geekblue" icon={<KeyOutlined />}>
                    功能: {viewingRolePermissions.length}
                  </Tag>
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {formatDateTime(viewingRole.createTime)}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {formatDateTime(viewingRole.updateTime)}
              </Descriptions.Item>
              <Descriptions.Item label="创建者">{viewingRole.createdBy || '暂无'}</Descriptions.Item>
              <Descriptions.Item label="描述">
                {viewingRole.remark || '暂无描述'}
              </Descriptions.Item>
            </Descriptions>

            {/* 权限统计信息 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <SafetyCertificateOutlined style={{ marginRight: 8 }} />
              权限统计
            </Title>
            <Descriptions bordered column={1} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="菜单权限数量">
                <Tag color="green" icon={<MenuOutlined />}>
                  {viewingRoleMenus.length} 个菜单
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="功能权限数量">
                <Tag color="geekblue" icon={<KeyOutlined />}>
                  {viewingRolePermissions.length} 个权限
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="总权限数量">
                <Tag color="purple" icon={<SafetyCertificateOutlined />}>
                  {viewingRoleMenus.length + viewingRolePermissions.length} 个权限
                </Tag>
              </Descriptions.Item>
            </Descriptions>

            {/* 菜单权限详情 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <MenuOutlined style={{ marginRight: 8 }} />
              菜单权限详情
            </Title>
            <div style={{ 
              padding: '16px', 
              backgroundColor: '#fafafa', 
              borderRadius: 8,
              border: '1px solid #f0f0f0',
              marginBottom: 24
            }}>
              {detailsLoading ? (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Spin size="small" />
                  <Text type="secondary" style={{ marginLeft: 8 }}>正在加载菜单权限...</Text>
                </div>
              ) : viewingRoleMenus.length > 0 ? (
                <div>
                  <div style={{ marginBottom: 12 }}>
                    <Text strong>拥有菜单权限（{viewingRoleMenus.length}个）：</Text>
                  </div>
                  <div>
                    {viewingRoleMenus.map(menuId => (
                      <Tag 
                        key={menuId} 
                        color="green" 
                        style={{ marginBottom: 8, padding: '4px 12px' }}
                        icon={<MenuOutlined />}
                      >
                        {getMenuName(menuId, menuTree)}
                      </Tag>
                    ))}
                  </div>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Text type="secondary">暂无菜单权限</Text>
                </div>
              )}
            </div>

            {/* 功能权限详情 */}
            <Title level={5} style={{ color: '#1890ff', marginBottom: 16 }}>
              <KeyOutlined style={{ marginRight: 8 }} />
              功能权限详情
            </Title>
            <div style={{ 
              padding: '16px', 
              backgroundColor: '#fafafa', 
              borderRadius: 8,
              border: '1px solid #f0f0f0'
            }}>
              {detailsLoading ? (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Spin size="small" />
                  <Text type="secondary" style={{ marginLeft: 8 }}>正在加载功能权限...</Text>
                </div>
              ) : viewingRolePermissions.length > 0 ? (
                <div>
                  <div style={{ marginBottom: 12 }}>
                    <Text strong>拥有功能权限（{viewingRolePermissions.length}个）：</Text>
                  </div>
                  <div>
                    {viewingRolePermissions.map(permissionCode => (
                      <Tag 
                        key={permissionCode} 
                        color="geekblue" 
                        style={{ marginBottom: 8, padding: '4px 12px' }}
                        icon={<SafetyCertificateOutlined />}
                      >
                        {getPermissionNameByCode(permissionCode, permissionTree)}
                      </Tag>
                    ))}
                  </div>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Text type="secondary">暂无功能权限</Text>
                </div>
              )}
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default Roles;